/**
 * Implémente les workflows.
 */
package ch.ifage.business.service;

import java.util.Iterator;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import org.slf4j.Logger;

import ch.ifage.business.dom.FirstStep;
import ch.ifage.business.dom.Step;
import ch.ifage.business.dom.Workflow;
import ch.ifage.business.dom.Workflows;

/**
 * @author Christian
 * 
 */
public class WorkflowsServiceImplJPAMySQL implements WorkflowsService {

	/**
	 * serial id.
	 */
	private static final long serialVersionUID = -5981460430924624414L;

	/**
	 * les Workflows.
	 */
	private Workflows wfs;

	/** The logger for the class. */
	@Inject
	private transient Logger logger;
	

	/** The entity manager that manages the persistence. */
	// The first line is for compatibility with JEE servers
	@PersistenceContext(unitName = "AnalyseFlux-Persistence")
	@Inject
	private EntityManager entityManager;

	/** Some post-construtor initializations. */
	@PostConstruct
	void init() {
		logger.info("Use the JPA implementation");
	}

	/**
	 * Constructeur vide.
	 */
	public WorkflowsServiceImplJPAMySQL() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ch.ifage.business.service.WorkflowService#getWfs()
	 */
	@Override
	//@Transactional
	public Workflows getWfsService() {
		CriteriaBuilder qb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Step> c = qb.createQuery(Step.class);
		TypedQuery<Step> query = entityManager.createQuery(c);

		List<Step> listOfAllStep = query.getResultList();

		// empty workflows
		wfs = new Workflows();

		// locate first step and add them to wfs
		for (Iterator<Step> iterator = listOfAllStep.iterator(); iterator.hasNext();) {
			Step step = (Step) iterator.next();
			if (step.getFather() == null) {
				Workflow wf = new Workflow((FirstStep) step);
				wfs.add(wf);
			}
		}

		// AnalyseFluxData data = new AnalyseFluxData();
		// setWfsService(data.getList());
		return wfs;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ch.ifage.business.service.WorkflowService#setWfs(ch.ifage.business.dom.Workflows)
	 */
	@Override
	public void setWfsService(final Workflows wfs) {
		this.wfs = wfs;
	}

}
